/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package navegador;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

/**
 *
 * @author SergioPeres
 */
public class UriRawContent {
    
    /**
     * Versão do protocolo utilizada
     */
    public final static String HTTP_VERSION = "HTTP/1.1";
    
    private Parametro p;
    
    public UriRawContent(Parametro p) {
        this.p = p;
    }
    
    /**
     * Realiza uma requisição HTTP e devolve uma resposta
     *
     * @return resposta do protocolo HTTP
     * @throws UnknownHostException quando não encontra o host
     * @throws IOException quando há algum erro de comunicação
     */
    public String getURIRawContent() throws UnknownHostException,
            IOException {
        Socket socket = null;
        try {
            // Abre a conexão
            socket = new Socket(p.getUrl(), p.getPort());
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));


            if (p.getMetodo().equalsIgnoreCase("POST")) {
                out.println(getPost(p));
            } else {
                out.println(getHead(p));
            }
            

            boolean loop = true;
            StringBuffer sb = new StringBuffer();

            // recupera a resposta quando ela estiver disponível
            while (loop) {
                if (in.ready()) {
                    int i = 0;
                    while ((i = in.read()) != -1) {
                        sb.append((char) i);
                    }
                    loop = false;
                }
            }
            return sb.toString();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }
    }
    
    public String getHead(Parametro p) {
        String head;
        
        // Envia a requisição
        head = p.getMetodo() + " " + p.getPath() + " " + HTTP_VERSION + "\n";
        head = head + "Host: " + p.getUrl() + ((p.getPort() == 80 ) ? "" : ":" + p.getPort()) + "\n";
        head = head + "Connection: Close \n";
        
        return head;
    }
    
    public String getPost(Parametro p) {
        String head;
        
        // Cabiçãlho dos POST
        head = p.getMetodo() + " " + p.getPath() + " " + HTTP_VERSION + "\n";
        head = head + "Host: " + p.getUrl() + ((p.getPort() == 80 ) ? "" : ":" + p.getPort()) + "\n";
        head = head + "User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 AeGAYgyeA/1.0\n";
        head = head + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n";
        head = head + "Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3\n";
        head = head + "Accept-Encoding: gzip, deflate\n";
        head = head + "Referer: http://" + p.getUrl() + ((p.getPort() == 80 ) ? "" : ":" + p.getPort()) + p.getPath() + "\n";
        head = head + "Connection: keep-alive \n";
        head = head + "Content-Type: application/x-www-form-urlencoded\n";
        head = head + "Content-Length: " + p.getDados().trim().length() + "\n";
        
        // Corpo dos POST
        head = head + p.getDados().trim() + "\n";
        
        return head;
    }
    
    
    public String excutePost(String targetURL, String urlParameters) {
        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", ""
                    + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            //Get Response	
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
